package com.example.nettry.demo.fault;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j2;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @date 2019-10-04 14:07
 */
@Log4j2
public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获得字符
        ByteBuf buf = (ByteBuf) msg;
        //创建二进制数组
        byte[] req = new byte[buf.readableBytes ( )];
        //读取
        buf.readBytes (req);
        //转换
        String body = new String(req, "UTF-8").substring(0, req.length
                - System.getProperty("line.separator").length());
        //打印
        System.out.println("The time server receive order : " + body
                + " ; the counter is : " + ++counter);
        //输出结果
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
                System.currentTimeMillis()).toString() : "BAD ORDER";
        //处理结果
        currentTime = currentTime + System.getProperty("line.separator");
        //从新设置缓冲区
        ByteBuf resp = Unpooled.copiedBuffer (currentTime.getBytes ( ));
        //应答消息...write只是把待发送的消息发送到缓冲数组中
        ctx.write (resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //
        log.info ("push--调用-将消息发送队列中消息写入到socketchannel中发送给对方");
        ctx.flush ( );
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error ("出现错误-关闭通道");
        ctx.close ();
    }
}
